<template>
  <div class="comments-analysis">
    <!-- 页面标题和筛选器 -->
    <div class="page-header">
      <div class="header-left">
        <h2>评分分析</h2>
        <a-tag class="ml-4" :color="getHealthScoreColor()"
          >商家健康分: {{ statistics.healthScore }}</a-tag
        >
      </div>
      <div class="header-right">
        <a-space>
          <a-select
            v-model="selectedProduct"
            placeholder="选择商品"
            style="width: 200px"
            allow-search
          >
            <a-option
              v-for="product in products"
              :key="product.id"
              :value="product.id"
            >
              {{ product.name }}
            </a-option>
          </a-select>
          <a-radio-group v-model="timeRange" type="button">
            <a-radio value="week">最近7天</a-radio>
            <a-radio value="month">最近30天</a-radio>
            <a-radio value="quarter">最近90天</a-radio>
            <a-radio value="custom">自定义</a-radio>
          </a-radio-group>
          <a-range-picker
            v-if="timeRange === 'custom'"
            v-model="customDateRange"
            style="width: 260px"
            @change="handleDateRangeChange"
          />
        </a-space>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="statistics-cards">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <statistic
              title="总评价数"
              :value="statistics.total"
              :value-style="{ color: '#2B5CE7' }"
            >
              <template #subtitle>
                <div class="stat-subtitle">
                  <span>昨日新增: +{{ statistics.yesterdayNew }}</span>
                </div>
              </template>
              <template #suffix>
                <span
                  class="trend"
                  :class="statistics.totalTrend > 0 ? 'up' : 'down'"
                >
                  <icon-up v-if="statistics.totalTrend > 0" />
                  <icon-down v-else />
                  {{ Math.abs(statistics.totalTrend) }}%
                </span>
              </template>
            </statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <statistic
              title="平均评分"
              :value="statistics.avgRating"
              :precision="1"
              :value-style="{ color: '#F7BA1E' }"
            >
              <template #subtitle>
                <div class="stat-subtitle">
                  <span
                    >环比: {{ statistics.ratingTrend > 0 ? "+" : ""
                    }}{{ statistics.ratingTrend }}%</span
                  >
                </div>
              </template>
              <template #suffix>
                <icon-star-fill style="color: #f7ba1e" />
              </template>
            </statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <statistic
              title="好评率"
              :value="statistics.goodRate"
              :precision="1"
              suffix="%"
              :value-style="{ color: '#14C9C9' }"
            >
              <template #subtitle>
                <div class="stat-subtitle">
                  <span>待回复好评: {{ statistics.pendingGoodReviews }}</span>
                </div>
              </template>
            </statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card
            class="stat-card"
            :bordered="false"
            :class="{ alert: statistics.badRate > 5 }"
          >
            <statistic
              title="差评率"
              :value="statistics.badRate"
              :precision="1"
              suffix="%"
              :value-style="{ color: '#F53F3F' }"
            >
              <template #subtitle>
                <div class="stat-subtitle">
                  <span class="urgent"
                    >待处理差评: {{ statistics.pendingBadReviews }}</span
                  >
                </div>
              </template>
            </statistic>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <a-row :gutter="16">
      <a-col :span="16">
        <!-- 评分趋势图表 -->
        <a-card class="chart-card" :bordered="false">
          <template #title>
            <div class="card-title-with-tabs">
              <span>评分趋势</span>
              <a-radio-group v-model="trendMetric" type="button" size="small">
                <a-radio value="rating">评分</a-radio>
                <a-radio value="volume">评价量</a-radio>
              </a-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="trend-chart"></div>
        </a-card>

        <!-- 评分分布图表 -->
        <a-card class="chart-card rating-distribution-card" :bordered="false">
          <template #title>
            <div class="card-title-with-tabs">
              <span>评分分布</span>
              <a-space>
                <a-tooltip content="评分分布反映了顾客的整体满意度">
                  <icon-info-circle />
                </a-tooltip>
              </a-space>
            </div>
          </template>
          <div class="rating-distribution">
            <div
              v-for="(count, rating) in ratingDistribution"
              :key="rating"
              class="rating-bar-item"
            >
              <div class="rating-info">
                <span class="rating-label">
                  <icon-star-fill :style="{ color: getRatingColor(rating) }" />
                  {{ rating }}星
                </span>
                <span class="percentage"
                  >{{ ((count / statistics.total) * 100).toFixed(1) }}%</span
                >
              </div>
              <div class="bar-wrapper">
                <div
                  class="bar"
                  :style="{
                    width: `${(count / Math.max(...Object.values(ratingDistribution))) * 100}%`,
                    backgroundColor: getRatingColor(rating),
                  }"
                >
                  <span class="count">{{ count }}条</span>
                </div>
                <div class="bar-bg"></div>
              </div>
            </div>
          </div>
          <div class="distribution-summary">
            <div class="summary-item">
              <span class="label">评分区间</span>
              <span class="value">{{ getScoreRange() }}</span>
            </div>
            <div class="summary-item">
              <span class="label">中位数</span>
              <span class="value">{{ getMedianScore() }}</span>
            </div>
            <div class="summary-item">
              <span class="label">标准差</span>
              <span class="value">{{ getStandardDeviation() }}</span>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 热门关键词 -->
        <a-card class="chart-card" :bordered="false">
          <template #title>
            <div class="card-title-with-tabs">
              <span>热门关键词</span>
              <a-radio-group v-model="keywordType" type="button" size="small">
                <a-radio value="positive">好评</a-radio>
                <a-radio value="negative">差评</a-radio>
              </a-radio-group>
            </div>
          </template>
          <div class="keywords-cloud">
            <a-space wrap :size="16">
              <a-tag
                v-for="keyword in filteredKeywords"
                :key="keyword.text"
                :style="{
                  fontSize: `${12 + keyword.weight * 4}px`,
                  color: getKeywordColor(keyword.weight, keywordType),
                }"
                @click="handleKeywordClick(keyword)"
              >
                {{ keyword.text }} ({{ keyword.count }})
              </a-tag>
            </a-space>
          </div>
        </a-card>

        <!-- 改进建议 -->
        <a-card class="chart-card" :bordered="false">
          <template #title>改进建议</template>
          <div class="improvement-suggestions">
            <a-collapse>
              <a-collapse-item
                v-for="(suggestion, index) in suggestions"
                :key="index"
                :header="suggestion.title"
              >
                <p>{{ suggestion.description }}</p>
                <a-progress
                  :percent="suggestion.priority"
                  :stroke-color="
                    suggestion.priority > 75
                      ? '#F53F3F'
                      : suggestion.priority > 50
                        ? '#FF7D00'
                        : '#16CA45'
                  "
                />
                <div class="suggestion-actions">
                  <a-button
                    type="primary"
                    size="small"
                    @click="handleSuggestionAction(suggestion)"
                  >
                    采取行动
                  </a-button>
                </div>
              </a-collapse-item>
            </a-collapse>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from "vue";
import { Statistic } from "@arco-design/web-vue";
import {
  IconUp,
  IconDown,
  IconStarFill,
  IconReply,
  IconInfoCircle,
} from "@arco-design/web-vue/es/icon";
import * as echarts from "echarts";

// 状态管理
const timeRange = ref("week");
const customDateRange = ref([]);
const selectedProduct = ref(null);
const trendMetric = ref("rating");
const keywordType = ref("positive");

// 统计数据
const statistics = reactive({
  total: 1286,
  totalTrend: 12.5,
  yesterdayNew: 45,
  avgRating: 4.5,
  ratingTrend: 2.3,
  goodRate: 92.3,
  badRate: 2.1,
  pendingGoodReviews: 12,
  pendingBadReviews: 3,
  healthScore: 95,
});

// 评分分布数据
const ratingDistribution = reactive({
  5: 820,
  4: 312,
  3: 98,
  2: 34,
  1: 22,
});

// 商品列表
const products = ref([
  { id: 1, name: "特色桂林米粉" },
  { id: 2, name: "桂林辣椒酱" },
  { id: 3, name: "桂林三花酒" },
]);

// 关键词数据
const keywords = ref([
  { text: "质量好", count: 156, weight: 1, type: "positive" },
  { text: "服务态度好", count: 98, weight: 0.8, type: "positive" },
  { text: "发货快", count: 87, weight: 0.7, type: "positive" },
  { text: "包装精美", count: 76, weight: 0.6, type: "positive" },
  { text: "性价比高", count: 65, weight: 0.5, type: "positive" },
  { text: "味道不好", count: 54, weight: 0.4, type: "negative" },
  { text: "发货慢", count: 43, weight: 0.3, type: "negative" },
  { text: "包装破损", count: 32, weight: 0.2, type: "negative" },
]);

// 改进建议
const suggestions = ref([
  {
    title: "提高发货速度",
    description: "近期有23%的差评提到发货速度慢，建议优化仓储物流流程",
    priority: 85,
  },
  {
    title: "改进包装",
    description: "有15%的评价提到包装问题，建议升级包装材料和方式",
    priority: 65,
  },
  {
    title: "优化产品口味",
    description: "部分顾客反馈产品口味有待改进，建议进行产品配方优化",
    priority: 45,
  },
]);

// 计算属性
const filteredKeywords = computed(() => {
  return keywords.value.filter((k) => k.type === keywordType.value);
});

// 方法
const getHealthScoreColor = () => {
  const score = statistics.healthScore;
  if (score >= 90) return "green";
  if (score >= 80) return "orange";
  return "red";
};

const getRatingColor = (rating) => {
  const colors = {
    5: "#14C9C9",
    4: "#16CA45",
    3: "#F7BA1E",
    2: "#FF7D00",
    1: "#F53F3F",
  };
  return colors[rating] || "#86909C";
};

const getKeywordColor = (weight, type) => {
  const baseHue = type === "positive" ? 200 : 0;
  return `hsl(${baseHue}, 70%, ${45 + weight * 10}%)`;
};

const handleKeywordClick = (keyword) => {
  // 实现关键词点击后的筛选逻辑
};

const handleSuggestionAction = (suggestion) => {
  // 实现采取行动的逻辑
};

// 图表相关
let trendChart = null;
const trendChartRef = ref(null);

const initTrendChart = () => {
  if (!trendChartRef.value) return;

  trendChart = echarts.init(trendChartRef.value);
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
    legend: {
      data: ["平均评分", "评价数量"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["3-10", "3-11", "3-12", "3-13", "3-14", "3-15", "3-16"],
    },
    yAxis: [
      {
        type: "value",
        name: "评分",
        min: 0,
        max: 5,
        interval: 1,
      },
      {
        type: "value",
        name: "数量",
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "平均评分",
        type: "line",
        smooth: true,
        data: [4.2, 4.5, 4.3, 4.6, 4.4, 4.8, 4.7],
        itemStyle: {
          color: "#2B5CE7",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(43, 92, 231, 0.2)",
              },
              {
                offset: 1,
                color: "rgba(43, 92, 231, 0)",
              },
            ],
          },
        },
      },
      {
        name: "评价数量",
        type: "bar",
        yAxisIndex: 1,
        data: [30, 42, 35, 50, 45, 55, 40],
        itemStyle: {
          color: "#86909C",
        },
      },
    ],
  };
  trendChart.setOption(option);
};

// 监听器
watch([timeRange, selectedProduct], ([newTimeRange, newProduct]) => {
  // 实现数据更新逻辑
});

watch(trendMetric, (newMetric) => {
  // 更新趋势图表显示的指标
});

// 生命周期钩子
onMounted(() => {
  initTrendChart();
  window.addEventListener("resize", () => {
    trendChart?.resize();
  });
});

onUnmounted(() => {
  trendChart?.dispose();
  window.removeEventListener("resize", () => {
    trendChart?.resize();
  });
});

// 评分统计方法
const getScoreRange = () => {
  const scores = Object.keys(ratingDistribution).map(Number);
  const min = Math.min(...scores);
  const max = Math.max(...scores);
  return `${min}~${max}分`;
};

const getMedianScore = () => {
  const scores = [];
  Object.entries(ratingDistribution).forEach(([score, count]) => {
    for (let i = 0; i < count; i++) {
      scores.push(Number(score));
    }
  });
  scores.sort((a, b) => a - b);
  const mid = Math.floor(scores.length / 2);
  return scores.length % 2 === 0
    ? ((scores[mid - 1] + scores[mid]) / 2).toFixed(1)
    : scores[mid].toFixed(1);
};

const getStandardDeviation = () => {
  const scores = [];
  let sum = 0;
  let count = 0;

  Object.entries(ratingDistribution).forEach(([score, num]) => {
    sum += Number(score) * num;
    count += num;
    for (let i = 0; i < num; i++) {
      scores.push(Number(score));
    }
  });

  const mean = sum / count;
  const squaredDiffs = scores.map((score) => Math.pow(score - mean, 2));
  const variance = squaredDiffs.reduce((a, b) => a + b) / scores.length;
  return Math.sqrt(variance).toFixed(2);
};
</script>

<style lang="scss" scoped>
.comments-analysis {
  padding: 24px;

  .page-header {
    @apply flex items-center justify-between mb-6;

    .header-left {
      @apply flex items-center;

      h2 {
        @apply text-xl font-medium m-0;
      }
    }
  }

  .statistics-cards {
    @apply mb-6;

    .stat-card {
      .stat-subtitle {
        @apply text-sm mt-2;
        color: var(--color-text-3);
      }

      .trend {
        @apply text-sm ml-2 flex items-center;

        &.up {
          color: #16ca45;
        }

        &.down {
          color: #f53f3f;
        }

        .icon {
          @apply mr-1;
        }
      }

      &.alert {
        animation: pulse 2s infinite;
      }
    }
  }

  .chart-card {
    @apply mb-6;

    .card-title-with-tabs {
      @apply flex items-center justify-between;

      .arco-tabs {
        margin-bottom: -16px;
      }
    }

    .rating-distribution {
      @apply space-y-4;

      .rating-bar {
        @apply flex items-center gap-4;

        .rating-label {
          @apply w-12 text-right text-sm;
          color: var(--color-text-3);
        }

        .bar-wrapper {
          @apply flex-1 flex items-center gap-2;

          .bar {
            @apply h-5 rounded transition-all duration-300;
          }

          .count {
            @apply text-sm;
            color: var(--color-text-3);
          }
        }

        .percentage {
          @apply w-16 text-sm;
          color: var(--color-text-3);
        }
      }
    }

    .trend-chart {
      @apply h-80;
    }

    .keywords-cloud {
      @apply p-4;

      :deep(.arco-tag) {
        @apply cursor-pointer transition-all duration-300;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    .improvement-suggestions {
      .suggestion-actions {
        @apply mt-4 text-right;
      }
    }
  }

  .rating-distribution-card {
    .rating-distribution {
      @apply space-y-6 py-4;

      .rating-bar-item {
        @apply flex flex-col gap-2;

        .rating-info {
          @apply flex items-center justify-between;

          .rating-label {
            @apply flex items-center gap-1 text-sm font-medium;
          }

          .percentage {
            @apply text-sm font-medium;
            color: var(--color-text-2);
          }
        }

        .bar-wrapper {
          @apply relative h-8 rounded-full overflow-hidden;
          background: var(--color-fill-2);

          .bar {
            @apply absolute left-0 top-0 h-full rounded-full transition-all duration-500 flex items-center;
            min-width: 40px;

            .count {
              @apply ml-3 text-sm text-white font-medium;
              text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            }

            &:hover {
              filter: brightness(1.1);
            }
          }

          .bar-bg {
            @apply absolute inset-0 opacity-10;
          }
        }
      }
    }

    .distribution-summary {
      @apply mt-6 pt-4 flex justify-between items-center;
      border-top: 1px solid var(--color-border);

      .summary-item {
        @apply flex flex-col items-center gap-1;

        .label {
          @apply text-sm;
          color: var(--color-text-3);
        }

        .value {
          @apply text-lg font-medium;
          color: var(--color-text-1);
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 63, 63, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 63, 63, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 63, 63, 0);
  }
}
</style>
